package controller.loginServlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bean.User;
import dao.util.UserCreate;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(LoginServlet.class);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captchaInput = req.getParameter("captcha");

        PrintWriter out = resp.getWriter();

        // ===== 1. 校验验证码 =====
        String sessionCaptcha = (String) req.getSession().getAttribute("captcha");
        if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captchaInput)) {
            out.write("验证码错误，请返回重新输入！");
            return;
        }
        // ===== 2. 验证用户名和密码 =====
        User flag;
        try {
            logger.info("使用UserMapper操作数据库");
            UserCreate userCreate = new UserCreate();
            flag = userCreate.getMapperClass().selectUser(username,password);
            userCreate.commitsession();
            logger.info("数据库事务提交");
            userCreate.closesession();
            logger.info("UserMapper关闭");
        } catch (Exception e) {
            System.out.println("出问题了");
            throw new RuntimeException(e);
        }
        if (flag != null) {
            logger.info("session对象创建");
            HttpSession session = req.getSession();
            session.setAttribute("user", flag);
            logger.info("session对象将User对象传递到域中");
            if (flag.getRole().equals("1")) {
                logger.info("成功登录到管理员界面");
                resp.getWriter().write("{\"status\":\"adminsuccess\",\"message\":\"管理员,登录成功\"}");
            }else  {
                logger.info("成功登录到用户界面");
                resp.getWriter().write("{\"status\":\"usersuccess\",\"message\":\"欢迎登陆，用户\"}");
            }

        } else {
                 resp.getWriter().write("{\"status\":\"error\",\"message\":\"登录失败\"}");
        }
    }
}
